using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Microsoft.Win32;

namespace XProject.GUI
{
    public partial class Manager : Form
    {

        //registty key to set application run at at Windows startup
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        DAO.DiaryDAO daoDiary= new XProject.DAO.DiaryDAO();
        Entity.DiaryItem diary = new XProject.Entity.DiaryItem();
        public static string startup_path = "";
        string preText="";
        public Manager()
        {
            InitializeComponent();
            MainForm.CurrentAccount = null;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.Hour>=1 && DateTime.Now.Hour<=3)
            {
                //only remind in early morning, not afternoon
                if(DateTime.Now.AddHours(12).Day==DateTime.Now.Day)
                if (DateTime.Now.Minute == 1)
                {
                    string msg = "^^";                    
                    msg += "\n^o^";                   
                    msg += "\n...";
                    msg += "It's too late. You should go to bed soon";
                    ntfManager.ShowBalloonTip(2000, "Manager", msg, ToolTipIcon.Info);
                }
            }
        }
        /// <summary>
        /// Show events in next 7 days
        /// </summary>
        public void ShowEvents()
        {
            DAO.EventDAO daoEvent = new XProject.DAO.EventDAO();
            IList<Entity.Event> events = null;
            if(MainForm.CurrentAccount==null)
            events=daoEvent.GetPublicEvent(DateTime.Today, DateTime.Today.AddDays(7), true);
            else
            events = daoEvent.GetEventByPeriodOfTime(MainForm.CurrentAccount.AccountID, DateTime.Today, DateTime.Today.AddDays(7));
        Util.LunarDate startDay = new XProject.Util.LunarDate(DateTime.Today);
        Util.LunarDate endDay = new XProject.Util.LunarDate(DateTime.Now.AddDays(7));
        IList<Entity.Event> levents = daoEvent.GetEventByLunarDate(1,(byte)startDay.Month,(byte)startDay.Day,(byte)endDay.Day);
        foreach (Entity.Event ev in levents) { events.Add(ev); }
            ntfManager.BalloonTipTitle = "Events in 7 days";
            string st = "";

            if (events.Count > 0)
            {
                
                int i = 0;
                foreach (Entity.Event ev in events)
                {
                    if (i == 0) st += ev.StartTime.ToShortDateString() + ": " + ev.Content;
                    else st += "\n" + ev.StartTime.ToShortDateString() + ": " + ev.Content;
                    if (ev.Priority <=2) st += "(*)";
                    i++;
                }
                ntfManager.BalloonTipText = st;
                ntfManager.ShowBalloonTip(8000);

            }
            else ntfManager.ShowBalloonTip(2000, "Event Manager", "There is no events in next seven days", ToolTipIcon.Info);
        }
        private void Manager_Load(object sender, EventArgs e)
        {
            startup_path = Application.StartupPath;
            //string icon=ConfigurationManager.AppSettings["icon"];
            //if (System.IO.File.Exists(icon)) { this.Icon = new Icon(icon); }
            int x = Screen.PrimaryScreen.WorkingArea.Width - this.Width - 5;
            int y = Screen.PrimaryScreen.WorkingArea.Height - this.Height - 10;
            this.Location = new Point(x, y);
            if (rkApp.GetValue("VAFApp") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRunAtStartUp.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRunAtStartUp.Checked = true;
            }
            DAO.AccountDAO daoAccount = new XProject.DAO.AccountDAO();
            timer1.Start();
            ntfManager.ContextMenuStrip = pupNotificator;           
                            
            if (daoAccount.Count() <= 0)
            {
                if (daoAccount.Message != "")
                {
                    MessageBox.Show(daoAccount.Message,"Error");
                    return;
                }
                MessageBox.Show("This is the first time the application is runned. You should create an administrator account now.");
                GUI.Registration frmReg = new Registration();
                frmReg.ShowDialog(this);               
            }
            ShowEvents();            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            EventManager frmEvent = new EventManager();
            frmEvent.Show();
        }

        private void Manager_FormClosed(object sender, FormClosedEventArgs e)
        {
           
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            
            if (e.KeyCode == Keys.Return)
            {
                preText = txtCommand.Text; 
                AnalysCommand();
                txtCommand.Text = "";
                
            }else if(e.KeyCode==Keys.Up) txtCommand.Text=preText;
        }
        //Add or update diary
        public void AddDiary(){
            int mode = 0;
            
            if (diary.ItemID <= 0)
            {
                mode = 1;
                diary.Account.AccountID = MainForm.CurrentAccount.AccountID;
                diary.Date=DateTime.Now;
                //set icon
                DAO.IconDAO daoIcon = new XProject.DAO.IconDAO();
                diary.Icon = daoIcon.GetIconByName("none");
            }
            else mode = 2;
            if (txtMessage.Text=="")
                {
                    MessageBox.Show("The content cannot be empty.");
                    return;
                }
                                 
            diary.Content =txtMessage.Rtf;  
            if (mode == 1)
            {
                
                if (daoDiary.Insert(diary) > 0)
                {
                    MessageBox.Show("Success");
                }
                else MessageBox.Show(daoDiary.Message);
            }
            else if (mode == 2)
            {    if (daoDiary.Update(diary) > 0)
                    MessageBox.Show("Updated successfully");
                else MessageBox.Show(daoDiary.Message);
            }
        }
        public void Login()
        {
            GUI.Login dlgLogin = new Login();
            if (dlgLogin.ShowDialog() == DialogResult.Yes)
            {
                MainForm.CurrentAccount = dlgLogin.Account;
                txtMessage.Text = "welcome, log in thanh cong roi do";
                lblUser.Text = MainForm.CurrentAccount.Username; 
            }
            else if (dlgLogin.DialogResult == DialogResult.No)
            {
                txtMessage.Text = "go sai cai gi noi roi, thu lai coi";
            }
        }

        //read command and do it
        public void AnalysCommand()
        {
           
            string cmdText = txtCommand.Text.ToLower().Trim();            
            string message = "";
            bool showMsg = true;
            if (cmdText == "") message = "Muon gi thi phai noi chu";
            else if (cmdText == "in" || cmdText == "login" || cmdText == "log in")
            {
                Login();
            }         
            else if (cmdText == "main")
            {
                MainForm frmMain = new MainForm();
                frmMain.Show();
                this.Hide();
            }
            else if (cmdText == "diary"||cmdText=="nk" || cmdText=="nhat ki"||cmdText=="dr")
            {
                if (MainForm.CurrentAccount == null) MessageBox.Show("Please login first");
                else
                {
                    diary = daoDiary.GetDiaryByDate(DateTime.Today, MainForm.CurrentAccount.AccountID);
                    txtMessage.Rtf = diary.Content;
                    txtMessage.ReadOnly = false;

                }
            }
            else if (cmdText.StartsWith("enc:"))
            {
                if (MainForm.CurrentAccount != null)
                {
                    string encText = Util.Encryptor.Encrypt(cmdText.Replace("enc:", "").Trim(), MainForm.CurrentAccount.Password);
                    txtMessage.Text = encText;
                    showMsg = false;
                }
                else
                {
                    message = "please login to use this fuction";
                    //showMsg = true;
                }
            }
            else if (cmdText == "ok" || cmdText == "end" || cmdText == "finish")
            {

                if (txtMessage.Rtf != diary.Content)
                    AddDiary();
                txtMessage.ReadOnly = true;
            }
            else if (cmdText == "event" || cmdText == "events" || cmdText == "su kien")
            {
                ShowEvents();
            }
            else message = "ai em ko hieu";
            if (showMsg) 
            txtMessage.Text = message;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            AnalysCommand();
        }

        private void ntfManager_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                
                Point p =e.Location;
                p.X = Screen.PrimaryScreen.WorkingArea.Width-pupNotificator.Width;
                p.Y = Screen.PrimaryScreen.WorkingArea.Height - pupNotificator.Height;                              
                ntfManager.ContextMenuStrip.Show(p);                  
                
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("The VAF will completely exit. Are you sure want to continue?", "Confirrm",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2) != DialogResult.Yes) 
                return;
            this.Dispose();
            Environment.Exit(0);
        }

        private void managerToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Show();         
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
          this.Hide();
        }

        private void managerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm frmMain = new MainForm();
            frmMain.Show();
        }

        private void ntfManager_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

        private void pupNotificator_Opening(object sender, CancelEventArgs e)
        {

        }

        private void mnuSaying_Click(object sender, EventArgs e)
        {
            GUI.SayingManager frmSaying = new SayingManager();
            frmSaying.Show();
        }

        private void lnkMain_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
            MainForm frmMain = new MainForm();
            frmMain.Show();
            this.Hide();
          
        }

        private void Manager_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                this.Dispose();
                Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void Manager_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {

                if (MainForm.CurrentAccount == null)
                {
                    lblUser.Text = "^^";
                    txtMessage.Text = "please login";
                }
                else
                {
                    lblUser.Text = MainForm.CurrentAccount.Username;
                    txtMessage.Text = "welcome";
                }
            }
        }

        private void lblEvent_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ShowEvents();
        }

        private void chkRunAtStartUp_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRunAtStartUp.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("VAFApp", Application.ExecutablePath.ToString());
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("VAFApp", false);
            }

        }

    }
}